econWidgets¶

A set of Jupyter widgets designed for teaching Mathematics and Statistics for Economics.

Imports and list of widgets available¶

In [1]:
import numpy as np
from econwidgets import (linear_widget, 
                         system_widget, 
                         quadratic_widget, 
                         logarithm_widget, 
                         exponential_widget,
                         inverse_widget,
                         quadratic_slope_widget,
                         derivative_widget,
                         multivar_widget,
                         matrix_widget,
                         taylor_widget,
                         utility_widget,
                         elasticities_widget,
                         slope_from_elasticities_widget,
                         tax_widget,
                         uk_IO_widget,
                         total_revenue_widget,
                         compound_interest_widget,
                         log_demand_widget,
                         profit_maximisation_widget,
                         plot_income_widget,
                         plot_dist_widget,
                         plot_hist_widget,
                         throw_dice_widget,
                         tree_widget,
                         birthday_widget,
                         norm_area_widget,
                         norm_binom_approx_widget,
                         clt_illustration_widget,
                         bias_variance_widget,
                         t_area_widget,
                         hypothesis_test_widget,
                         error_type_widget,
                         error_tradeoff_widget,
                         scatter_plot_widget)

Mathematics widgets¶

linear_widget¶

Draws a linear function in Cartesian space. The slope and intercept can be provided, or determined from 2 points in that space.

In [2]:
linear_widget(xMax_init = 16, yMax_init = 16, a_init = 0, b_init = 0, Aflag_init = True, 
                  xA_init = -3, yA_init = -14, Bflag_init = True, xB_init = 5, yB_init = 10, 
                  eqFlag1_init = False, eqFlag2_init = False)

system_widget¶

Draws a system of two linear equations (e.g. demand/supply) and determines the solution if the intersetion exists. Also indicates cases where there are no solutions or infinite solutions.

In [3]:
system_widget(xMax_init = 15, yMax_init = 15, a_init = 4, b_init = 6, c_init = 38, 
                  d_init = -2, e_init = 2, f_init = -4)

quadratic_widget¶

Draws a quadratic $ax^2 + bx+c$ given parameters $a,b,c$

In [4]:
quadratic_widget()

logarithm_widget¶

Draws a logarithm plot given a choice of base. Allows multiple logarithms as well as 3 points on each curve to illustrate $\log(AB) = \log(A) + \log(B)$

In [5]:
logarithm_widget()

exponential_widget¶

Draws an exponential plot given a choice of base. Allows multiple exponentials.

In [6]:
exponential_widget(xMax_init = 10, yMax_init = 1000, bases_init = ['2','None','None'])

inverse_widget¶

Draws an exponential and logarithm plot given a choice of base, to illustrate the fact they are each other's inverse

In [7]:
inverse_widget()

quadratic_slope_widget¶

Illustrate the calculation of slopes for non-linear functions in a quadratic setting. Allows for the calculation of the slope between two points on the curve to illustrate the intuition behind the limit definition of derivatives.

In [8]:
quadratic_slope_widget()

derivative_widget¶

Plots the first and second-order derivatives of an arbitrary cubic, including turning points.

In [9]:
derivative_widget(xMin_init = -3, xMax_init = 3, yMin_init = -10, yMax_init = 10, areaFlag_init = True)

multivar_widget¶

3D plot of a bivariate function (sines, exponentials, true maximum/minimum, 2 different saddle points). The 3D surface can be sliced along the $x$ and $y$ coordinates of an arbitrary point to illustrate the concept of partial derivatives.

In [10]:
multivar_widget(elev_init = 40, azim_init = 50, yCut_init = True)

matrix_widget¶

Geometric illustration of 2x2 matrices as transformations of 2D space

In [11]:
matrix_widget(A_base = [[0.7071,0.7071],[-0.7071,0.7071]], B_base = [[1,1.25],[0,1]],mode_init = 'AB')

taylor_widget¶

Taylor expansion plot for sines, exponetial and logarithms.

In [12]:
taylor_widget(xMin_init = -2, xMax_init = 6, yMin_init = -4, yMax_init = 4, func_init = 'Logarithm', numTerms_init = 18)

Economic application widgets¶

utility_widget¶

3D plot / 2D plot of a constrained optimisation problem

In [13]:
utility_widget(a_init = 0.3, elev_init = 15, azim_init = 260, zCut_init = True, constraintCut_init = True)

elsticities_widget¶

Linear supply/demand diagram with elasticity calculation

In [14]:
elasticities_widget(Qmax_init = 15, Pmax_init = 30, Qval_init = 6, a_d_init = 0.5,
    b_d_init = 22, a_s_init = 0.75, b_s_init = 10, Dflag_init = True, Sflag_init = True)

slope_from_elasticities_widget¶

Supply/demand diagram showing approximate supply/demand around equilibrium points given elasticities

In [15]:
slope_from_elasticities_widget()

tax_widget¶

Supply/demand diagram showing the impact of a flat tax, including tax revenue from producers/consumers and deadweight loss. Useful for showing how share of the tax burden depends on relative elasticities.

In [16]:
tax_widget(Qmax_init = 10, Pmax_init = 30, Tval_init = 10, a_d_init = 1.5,
    b_d_init = 25, a_s_init = 35, b_s_init = -175, Rflag_init = True, Lflag_init = True)

uk_IO_widget¶

Matrix-based analysis of shock propagation through the UK economiy, based on the ONS' 2017 input-output supply and use tables for the UK.

In [17]:
uk_IO_widget(shockSector_init = ['Financial and insurance', 'Professional and support activities'], 
             shockSign_init = 'Negative', shockSize_init = 25, NumRounds_init = 5, Normalise_init = False, 
                 plotType_init = 'Shocks over time')
In [18]:
uk_IO_widget(shockSector_init = ['Financial and insurance', 'Professional and support activities'], 
             shockSign_init = 'Negative', shockSize_init = 25, NumRounds_init = 5, Normalise_init = False, 
                 plotType_init = 'Cumulative shocks')

total_revenue_widget¶

plots total revenue as a quadratic for a linear demand curve

In [19]:
total_revenue_widget()

compound_interest_widget¶

illustrates how compounding interest over shorter time-periods convergest to the exponential

In [20]:
compound_interest_widget(numTermsStr_init = '1,4,10',expFlag_init = True)

log_demand_widget¶

illustrates how isoelastic functions, which produce non-linear demand functions, are actually linear in logarithmic space

In [21]:
log_demand_widget()

profit_maximisation_widget¶

illustrates profit maximisation using both the zero derivative of profit and using marginal revenue / marginal cost.

In [22]:
profit_maximisation_widget()

plot_income_widget¶

Plots the empirical distribution of UK household income and provides descriptive statistics. Requires a CSV file containing the income brackets and counts (FY 2017 and 2020 provided)

In [23]:
plot_income_widget(loc = 'assets/income2017.csv')

Statistics widgets¶

plot_dist_widget¶

Plots Binonmial, Normal, Lognormal and Student t distribution, with descriptive statistics

In [24]:
plot_dist_widget(
    dist_1_init = 'Normal', d1_p1_init = 3, d1_p2_init = 0.5, d1_frmt_init = 'r-',
    dist_2_init = 'Lognormal', d2_p1_init = 1, d2_p2_init = 0.4, d2_frmt_init = 'g--',
    stats_init = False)

plot_hist_widget¶

Plots a histogram of data, requires a CSV file with raw observations.

In [25]:
plot_hist_widget(data_loc = 'assets/marks.csv', class_init = '0,40,60,70,100',x_label = 'Final Grades',
                 title = 'Histogram of grades by classification' )

throw_dice_widget¶

Plots a bar chart for frequencies of N throws of 3 different dice, only one of which is fair. Useful for showing how slowly empirical frequencies converge to probabilities.

In [26]:
throw_dice_widget(1,100) # (a,b) -> Throw dice a b times. 3 dice available

tree_widget¶

Shows a tree representatinon of sequential events, useful for explaining Bayes rule in a practical setting, where we want the probability ofthe first event having only observed the second.

In [27]:
tree_widget("[ ['S','H',0.001] , ['P','N',[0.99,0.01]] ]", popSize_init = 1000000)

birthday_widget¶

Shows a visual representatinon of the birthday problem, i.e. the probability that a in group of people no birthday is shared. This probability falls to 0 much faster than one might naively expect (k=23 already gives you a 50/50 chance).

In [28]:
birthday_widget(k_init=19)

norm_area_widget¶

Shows how to calculate probabilities for a normally-distributed variate as areas under the pdf of an arbitrary normal distribution. Setting mu_init = 0 and sig2_init = 1 provides a standard normal.

In [29]:
norm_area_widget(mu_init=60, sig2_init=49, X_cond_init = '49 < X < 51')

norm_binom_approx_widget¶

Illustrates the convergence of the binomial distribution $B(n,p)$ to a normal distribution $N(np,np(1-p))$ for large $n$.

In [30]:
norm_binom_approx_widget(n_init = 15, p_init = 0.4, show_norm_init = True)

clt_illustration_widget¶

Illustrates the central limit theorem by calculating the mean or sum of $N$ samples of size $n$ taken from a candidate distribution. The candidate is plotted on the left, the MC frequencies/theoretical Normal distribution is plotted on the right.

In [31]:
clt_illustration_widget(dist_init = 'Exponential', p1_init = 0.1, p2_init = 0, 
                        n_init=100, N_init = 10000, normalise_init = True)

clt_illustration_widget¶

Illustrates the central limit theorem by calculating the mean or sum of $N$ samples of size $n$ taken from a candidate distribution. The candidate is plotted on the left, the MC frequencies/theoretical Normal distribution are plotted on the right.

In [32]:
clt_illustration_widget(dist_init = 'Exponential', p1_init = 0.1, p2_init = 0, 
                        n_init=100, N_init = 10000, normalise_init = True)

bias_variance_widget¶

Illustrates the differences in bias/variance provided by various estimators of the sample mean, by calculating the mean and median of $N$ samples of size $n$ taken from a candidate distribution. The candidate is plotted on the left, the MC frequenciesare plotted on the right.

In [33]:
bias_variance_widget(dist_init = 'Normal', p1_init = 50, p2_init = 25, n_init=10, N_init = 20000)

t_area_widget¶

Shows the probabilities provided by a Student's T distribution compared to standard normal for a given sample size $n$ and Z-score. Useful for showing how standard normal confidence intervals are overconfident in small samples.

In [34]:
t_area_widget(nu_init=3, frmt_init='b-', X_cond_init = '-1.96 < Z < 1.96')

hypothesis_test_widget¶

Plots the accept/reject regions and decision information for a hypothesis test given the sampling distribution and the alternate hypothesis. Provides test statistic and critical value, can handle one/two tailed tests and automatically uses the student T if $n<30$.

In [35]:
hypothesis_test_widget(n_init = 8, H0_init=120, Xbar_init=105, sig2_init=16**2, 
                           tails_init='mu ~= 120', alpha_init = 0.95, t_init=False)

error_type_widget¶

Basic illustration of type I and type II errors based on a noisy scatter plot. Helpful to illustrate (a) the origin of theypeI/II errors when uncertainty is present and (b) that changing the decision threshold to reduce one type of error MUST increase the other type of error.

In [36]:
error_type_widget(noise_init = 0.25, gap_init = 0, threshold_init = 0.2, N_init = 5000)

error_tradeoff_widget¶

A more traditional illustration of typeI/II error trade-offs. Note that this widget illustrates the tradeoff for one-tailed tests as well as two tailed, especially the fact that when picking a one-tailed test the extra power in the test comes at the cost of a total loss of power in the direction we assume cannot happen.

In [37]:
error_tradeoff_widget(muH0_init = 0, muH1_init=3, muH2_init=0, sig2_init=1, 
                           Zcrit_init = 1.645, useH2_init = False, twotail_init=False)
In [38]:
error_tradeoff_widget(muH0_init = 0, muH1_init=3, muH2_init=-3.5, sig2_init=1, 
                           Zcrit_init = 1.96, useH2_init = True, twotail_init=True)

scatter_plot_widget¶

Bivariate scatter plot, accepts list of numpy vectors (with option to add normaql noise) or a path to a csv file. Options include display of the correlation and its significance, and a regression line with manual or automatic OLS parameters.

In [39]:
X = np.random.rand(500)
scatter_plot_widget(data = [X,-0.5*X], add_noise_init = 0.1, x_label = r'Variable $X$', y_label = r'Variable $Y$',
                    rho_init = True, regr_init=True, ols_init = True)
In [ ]: